<template>
  <div class="app_container">
    <!-- 头部 -->
    <Header></Header>
    <Goods
      v-for="item in list"
      :key="item.id"
      :id="item.id"
      :title="item.goods_name"
      :pic="item.goods_img"
      :price="item.goods_price"
      :status="item.goods_state"
      :count="item.goods_count"
      @status-change="getNewStatus"
    >
    <Counter :num="item.goods_count" @add="addCount(item,$event)" @sub="subCount(item,$event)"></Counter>
    </Goods>
    <Footer :full="fullStatus" :allPrice="amt" :allCount="allCount" @changeStatus="getNewFullStatus" ></Footer>
  </div>
</template>

<script>
//导入axios网络请求
import axios from "axios";
//导入Header组建
import Header from "@/components/Header/Header.vue"
import Goods from "@/components/Goods/Goods.vue"
import Footer from "@/components/Footer/Footer.vue"
import bus from '@/components/EventBus.js'
import Counter from '@/components/Counter/Counter.vue'

export default {
  data() {
    return {
      list: [],
    };
  },
  computed:{
    fullStatus(){
      return this.list.every(item => item.goods_state)
    },
    amt(){
      return this.list.filter(item=>item.goods_state)
      .reduce((total ,item)=>(total += item.goods_price * item.goods_count),0)
    },
    allCount(){
      return this.list.filter(item=>item.goods_state)
      .reduce((sum ,item)=>(sum+=item.goods_count),0)
    }
  },
  methods: {
    async initCartList() {
      const { data: res } = await axios.get("https://www.escook.cn/api/cart");
      console.log(res);
      if (res.status === 200) {
        this.list = res.list;
      }
    },
    getNewStatus(val){
      console.log(val);

      this.list.some(item =>{
          if (item.id === val.id) {
            item.goods_state = val.status
            return true;
          }
      })
    },
    getNewFullStatus(val){
      this.list.forEach(element => {
        element.goods_state = val
      });
    },
    addCount(item , val){
      item.goods_count =val
    },
    subCount(item , val){
        item.goods_count =val
    },
  },
  created() {
    this.initCartList();
    bus.$on("add",(val)=>{
      this.list.some(item=>{
        if (item.id === val.id) {
          item.goods_count++
        }
      })
    });
    bus.$on("sub",(val)=>{
      this.list.some(item=>{
        if (item.id === val.id) {
          if (item.goods_count>1) {
            item.goods_count--
          }else{
            alert("不能减了")
          }
        }
      })
    })
  },
  components: {
    Header,
    Goods,
    Footer,
    Counter
  },
};
</script>

<style lang="less" scoped>
.app_container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>>